package org.sxm.cloud.fegin;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.sxm.cloud.exception.BizException;
import org.sxm.cloud.result.ApiResult;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Objects;

/**
 * @Description 自定义 OpenFegin解码器
 * @Author xmSheng
 * @Date 2024/1/23
 */
public class FeginResponseDecoder implements Decoder {

    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        if (Objects.isNull(response.body())) {
            return null;
        }
         ApiResult result = JSONUtil.toBean(IoUtil.readUtf8(response.body().asInputStream()), ApiResult.class);
        if (!result.isSuccess()) {
            throw new BizException(result.getCode(), result.getMessage());
        }
        if(isBase(type)){
            return (Object)result.getData();
        }
        return ((JSONObject) result.getData()).toBean(type);
    }

    public static boolean isBase(Type type) {
        return Byte.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                byte.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                Short.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                short.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                Integer.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                int.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                Long.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                long.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                Double.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                double.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                Float.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                float.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                Boolean.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                boolean.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                char.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                Character.class.toString().equalsIgnoreCase(type.getTypeName()) ||
                String.class.toString().equalsIgnoreCase(type.getTypeName());
    }




}
